/*
 * @Author: wuqingchun
 * @Date: 2023-08-17 10:53:59
 * @Description: 
 * @LastEditors: wuqingchun
 * @LastEditTime: 2023-12-29 02:27:15
 */
#include <stdlib.h>

#include "ftpc_buf.h"

FTPC_BUF_S* FTPC_buf_Get(FTPC_BUF_HEAD_S* pstBufHead)
{
    FTPC_BUF_S* pstBuf = pstBufHead->pstTail;

    if (pstBuf != NULL && pstBuf->ulDataSize < pstBufHead->ulBufSize)
    {
        return pstBuf;
    }

    pstBuf = malloc(sizeof(FTPC_BUF_S) + pstBufHead->ulBufSize);
    if (pstBuf != NULL)
    {
        pstBuf->pstNext = NULL;
        pstBuf->ulDataSize = 0;
        pstBuf->pcBuf = (char *)pstBuf + sizeof(FTPC_BUF_S);
        if (pstBufHead->pstHead == NULL)
        {
            pstBufHead->pstHead = pstBuf;
            pstBufHead->pstTail = pstBuf;
        }
        else
        {
            FTPC_BUF_S* pstTail = pstBufHead->pstTail;
            pstTail->pstNext = pstBuf;
            pstBufHead->pstTail = pstBuf;
        }
    }

    return pstBuf;
}

void FTPC_buf_Fini(FTPC_BUF_HEAD_S* pstBufHead)
{
    FTPC_BUF_S* pstBuf = pstBufHead->pstHead;

    while (pstBuf != NULL)
    {
        pstBufHead->pstHead = pstBuf->pstNext;
        free(pstBuf);
        pstBuf = pstBufHead->pstHead;
    }

    pstBufHead->pstHead = NULL;
    pstBufHead->pstTail = NULL;
}